package com.vote.controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.rest.Post;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.vote.annotation.TopListRequired;
import com.vote.model.User;
import com.vote.services.UserService;
import com.vote.utils.HostHelper;


public class UserController {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
   
    @TopListRequired
    public String index(){
        return "register";
    }
    
    public String register(Invocation inv,User user){
        int id = -1;
        try {
            id = userService.insertUser(user);
        } catch (Exception e) {
            logger.info("insert user fail!\n", e);
        }
        logger.debug("add new user : user name = " + user.getUserName() + "; user password = " + user.getUserPassword() + "; user email = " + user.getUserEmail());
        HostHelper.setHost(inv.getRequest(), user);
        return "r:"+inv.getModel("HomeUrl");
    }
    
    @Post("checkName")
    public String checkName(Invocation inv,
    		@Param("userName") String userName)
    {
    	JSONObject jo = new JSONObject();
		
    	if(userService.checkUserName(userName))
    	{
    		jo.put("code", 1);
    	    return String.format("@%s", jo.toString());
    	}else
    	{
    		jo.put("code", 0);
    		return String.format("@%s", jo.toString());
    	}
    	
    }
}
